//
//  KViewController.m
//  NeiHan
//
//  Created by 柯平 on 2017/3/11.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KViewController.h"
#import "SVProgressHUD.h"
#import "MBProgressHUD+KP.h"
#import "AFNetworkReachabilityManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import "KNavigationController.h"
#import <SDImageCache.h>


#define IS_MB 1

@interface KViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property(nonatomic,weak)MBProgressHUD* mbHUD;
@property(nonatomic,assign)HudShowType  hudType;

@end

@implementation KViewController

-(AppDelegate *)app
{
    if (!_app) {
        _app = (AppDelegate*)[UIApplication sharedApplication].delegate;
    }
    return _app;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
        
    if ([self respondsToSelector:@selector( setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //设置背景色
    self.view.backgroundColor = KBackColor/*[UIColor colorWithRed:244/255.0 green:245/255.0 blue:246/255.0 alpha:1.0]*/;
    
    self.view.height-=64;
}

#pragma mark - 键盘管理
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



#pragma mark - 网络监控
-(BOOL)isNetworkAvailable{
    return [YYReachability reachability].isReachable;
}

#pragma mark - 数据处理
-(void)getData{
    if (!self.isNetworkAvailable) {
        KLog(@"暂无网络，请检查网络设置！");
        [self showText:@"暂无网络，请检查网络设置！"];
        return;
    }
    
    
}

-(void)requestFinished:(__kindof KBaseRequest *)request{
    if (self.page <= 1) {
        [self.data removeAllObjects];
    }
}
-(void)requestFailed:(__kindof KBaseRequest *)request{
    KLog(@"请求失败:%@",request.error.localizedDescription);
    [self showError:request.error];
    self.page --;
}


#pragma mark - 懒加载
-(KWhiteNaviBar *)whiteNaviBar
{
    if (!_whiteNaviBar) {
        _whiteNaviBar = [[KWhiteNaviBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
        @weakify(self);
        [self.view bringSubviewToFront:_whiteNaviBar];
        _whiteNaviBar.backgroundColor = kWhiteColor;
        _whiteNaviBar.hidden = YES;
        [self.view addSubview:_whiteNaviBar];
        _whiteNaviBar.KClickBack = ^(BOOL isBack) {
            [weak_self.navigationController popViewControllerAnimated:isBack];
        };
    }
    return _whiteNaviBar;
}
-(HudShowType)hudType{
    if (!_hudType) {
        _hudType = [[KAppConfig sharedConfig] hudType];
    }
    return _hudType;
}
-(UIScrollView *)scrollView{
    if (!_scrollView) {
        UIScrollView* scrl = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        scrl.backgroundColor = [UIColor clearColor];
        scrl.showsVerticalScrollIndicator = NO;
        scrl.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:scrl];
        _scrollView = scrl;
    }
    return _scrollView;
}

-(NSInteger)page{
    if (!_page) {
        _page = 1;
    }
    return _page;
}
-(NSInteger)totalPage{
    if (!_totalPage) {
        _totalPage = 1;
    }
    return _totalPage;
}

-(NSInteger)pageSize{
    if (!_pageSize) {
        _pageSize = 10;
    }
    return _pageSize;
}
-(NSMutableArray *)data{
    if (!_data) {
        _data = [NSMutableArray array];
    }
    return _data;
}
-(MBProgressHUD *)mbHUD{
    if (!_mbHUD) {
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view?:self.view animated:YES];
        _mbHUD = hud;
    }
    return _mbHUD;
}


#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    [[[YYWebImageManager sharedManager] cache].diskCache removeAllObjects];
    [[[YYWebImageManager sharedManager] cache].memoryCache removeAllObjects];
}

#pragma mark - 安全引用
-(void)dealloc{
    
}

#pragma mark - 子控制器管理
-(void)addChildVc:(UIViewController *)childVc{
    if (![childVc isKindOfClass:[UIViewController class]]) return;
    [self addChildViewController:childVc];
    [childVc willMoveToParentViewController:self];
    [self.view addSubview:childVc.view];
    childVc.view.frame = self.view.bounds;
}
-(void)removeChildVc:(UIViewController *)childVc{
    if (![childVc isKindOfClass:[UIViewController class]]) return;
    [childVc.view removeFromSuperview];
    [childVc willMoveToParentViewController:nil];
    [childVc removeFromParentViewController];
}

#pragma mark - HUD
-(void)showText:(NSString *)text{
    [self hideHUD];
    if (self.hudType == HudShowTypeMB) {
        [MBProgressHUD showMsg:text];
    }else if (self.hudType == HudShowTypeSV){
        [SVProgressHUD setInfoImage:nil];
        
        [SVProgressHUD setMinimumDismissTimeInterval:text.length*0.2 > 2.0 ? text.length*0.2 : 2.0];
        [SVProgressHUD showInfoWithStatus:text];
        
    }else if (self.hudType == HudShowTypeCustom){
        
    }else{
        
    }
}

-(void)showLoading{
    [self hideHUD];
    if (self.hudType == HudShowTypeSV) {
        [SVProgressHUD setMinimumDismissTimeInterval:30];
        [SVProgressHUD show];
    }else if (self.hudType == HudShowTypeMB){
        [MBProgressHUD showLoading];
    }
}

-(void)showLoading:(NSString *)loading{
    [self hideHUD];
    [MBProgressHUD showLoading:loading];
}

-(void)showLoading:(NSString *)loading timeout:(NSTimeInterval)time{
    [self hideHUD];
    if (time > 0) {
        if (self.hudType == HudShowTypeMB) {
            [MBProgressHUD showLoading:loading timeout:time];
        }else if (self.hudType == HudShowTypeSV){
            [SVProgressHUD setMinimumDismissTimeInterval:30];
            [SVProgressHUD showWithStatus:loading];
        }
    }
}

-(void)hideHUD{
    
    if (self.hudType == HudShowTypeMB) {
        [MBProgressHUD hideHud];
    }else if (self.hudType == HudShowTypeSV){
        [SVProgressHUD dismiss];
    }
}

-(void)showSuccess:(NSString *)text{
    [self hideHUD];
    if (self.hudType == HudShowTypeMB) {
        [MBProgressHUD showSuccessText:text];
    }else if (self.hudType == HudShowTypeSV){
        [SVProgressHUD setMaximumDismissTimeInterval:2.5];
        [SVProgressHUD setMinimumDismissTimeInterval:1.5];
        [SVProgressHUD showSuccessWithStatus:text];
    }
}

-(void)showErrorText:(NSString *)text errCode:(NSInteger)errCode
{
    if (errCode == 84512) {
        [MBProgressHUD showErrorText:text];
        [self changeRootToLoginViewController];
    }else{
        [self showErrorText:text];
    }
}

-(void)showErrorText:(NSString *)text{
    [self hideHUD];
    if (self.hudType == HudShowTypeMB) {
        [MBProgressHUD showErrorText:text];
    }else if (self.hudType == HudShowTypeSV){
        [SVProgressHUD showErrorWithStatus:text];
    }
}
-(void)showError:(NSError *)error{
    [self hideHUD];
    if (self.hudType == HudShowTypeMB) {
        [MBProgressHUD showError:error];
    }else if (self.hudType == HudShowTypeSV){
        [SVProgressHUD setInfoImage:nil];
        NSString* text = error.localizedDescription;
        [SVProgressHUD setMinimumDismissTimeInterval:text.length*0.2 > 2.5 ? text.length*0.1 : 2.5];
        [SVProgressHUD showInfoWithStatus:text];
    }
    
}

-(void)showAlertInfo:(NSString *)info{
    if ([info isNotBlank]) return;
    //NSTimeInterval time = info.length*0.3;
    
}
-(void)checkCameraAvailability:(void (^)(BOOL))block{
    BOOL available = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusAuthorized) {
        available = YES;
    }else if (authStatus == AVAuthorizationStatusDenied){
        available = NO;
    }else if (authStatus == AVAuthorizationStatusRestricted){
        available = NO;
    }else if (authStatus == AVAuthorizationStatusNotDetermined){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (block) {
                block(granted);
            }
        }];
        return;
    }
    if (block) {
        block(available);
    }
}
-(void)getImageWIthChannel:(UIImagePickerControllerSourceType)sourceType{
    switch (sourceType) {
        case UIImagePickerControllerSourceTypeCamera:
        {
        [self getImageWithType:UIImagePickerControllerSourceTypeCamera];
        }
            break;
        case UIImagePickerControllerSourceTypePhotoLibrary:
        {
        [self getImageWithType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
            break;
        case UIImagePickerControllerSourceTypeSavedPhotosAlbum:
        {
        [self getImageWithType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        }
            break;
        default:
            break;
    }
}


-(void)getImageWithType:(UIImagePickerControllerSourceType)sourceType{
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        if (UIImagePickerControllerSourceTypePhotoLibrary == sourceType) {
            [self showErrorText:@"请允许访问相册"];
        }else if (UIImagePickerControllerSourceTypeCamera == sourceType){
            [self showErrorText:@"请允许使用相机"];
        }
    }else{
        UIImagePickerController* imagePicker = [UIImagePickerController new];
        imagePicker.delegate = self;
        imagePicker.sourceType = sourceType;
        imagePicker.allowsEditing = YES;
        if (UIImagePickerControllerSourceTypeCamera == sourceType) {
            imagePicker.showsCameraControls = YES;
            imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        imagePicker.mediaTypes = @[(NSString*)kUTTypeImage];
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage* image = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        if ([self.imageDelegate respondsToSelector:@selector(didGetImage:)]) {
            [self.imageDelegate didGetImage:image];
        }
    }];
}

-(BOOL)checkUserLoginOrNot{
    if (![KAppConfig sharedConfig].logined) {
        KAlertView* alert = [[KAlertView alloc]initWithTitle:@"提示" content:@"您尚未登录，是否立即登录？" placeholder:nil style:KAlertViewAlert];
        @weakify(self);
        alert.ClickBlock = ^(BOOL confirm, NSString* text){
            if (confirm) {
                //KNavigationController* navi = [[KNavigationController alloc]initWithRootViewController:[KPhoneFastLoginViewController new]];
                //[weak_self presentViewController:navi animated:YES completion:nil];
            }
        };
        [alert showInView:self.view];
    }
    return [KAppConfig sharedConfig].logined;
}



@end
